﻿namespace Away.Configs.Repositories.Implements;

[ServiceInject(ServiceLifetime.Scoped)]
public class ConfigRepository : ConfRepositoryBase, IConfigRepository
{
    public ConfigRepository(ConfigsDbContext context) : base(context)
    {
    }
    public bool AddConfig(ConfConfiguration model)
    {
        Add(model);
        return Save();
    }
    public bool AddGroup(ConfGroup model)
    {
        Add(model);
        return Save();
    }
    public bool DeleteConfig(int[] ids)
    {
        var items = Query<ConfConfiguration>().Where(o => ids.Contains(o.Id)).ToArray();
        if (!items.Any())
        {
            return true;
        }
        Remove(items);
        return Save();
    }
    public bool DeleteGroup(int[] ids)
    {
        var items = Query<ConfGroup>().Where(o => ids.Contains(o.Id)).ToArray();
        if (!items.Any())
        {
            return true;
        }
        Remove(items);
        return Save();
    }
    public List<Configuration> GetConfigList(string env)
    {
        return Query<ConfConfiguration>()
            .Where(o => o.Env == env)
            .Select(o => new Configuration
            {
                Key = o.Key,
                Value = o.Value,
                ValueType = o.ValueType,
            }).ToList();
    }
    public ApiResult GetConfigPage(ConfigSearch search)
    {
        var cond = CondBuilder.New<ConfConfiguration>(true)
            .And(search.Status.HasValue, o => o.Status == search.Status)
            .And(search.GroupId > 0, o => o.GroupId == search.GroupId)
            .And(!string.IsNullOrWhiteSpace(search.Env), o => o.Env == search.Env)
            .And(!string.IsNullOrWhiteSpace(search.Key), o => o.Key.Contains(search.Key));

        var tb = Query<ConfConfiguration>().Where(cond);

        var total = tb.Count();
        var items = tb.OrderByDescending(o => o.Id).Page(search).ToList();
        return ApiResult.Page(total, items);
    }
    public List<string> GetEnvList()
    {
        return Query<ConfGroup>().Select(o => o.Env).Distinct().ToList();
    }
    public List<ConfGroup> GetGroupList()
    {
        return Query<ConfGroup>().ToList();
    }
    public ApiResult GetGroupPage(GroupSearch search)
    {
        var cond = CondBuilder.New<ConfGroup>(true)
            .And(!string.IsNullOrWhiteSpace(search.Env), o => o.Env == search.Env)
            .And(!string.IsNullOrWhiteSpace(search.Name), o => o.Name.Contains(search.Name))
            .And(search.Status.HasValue, o => o.Status == search.Status);

        var tb = Query<ConfGroup>().Where(cond);
        var total = tb.Count();
        var items = tb.OrderByDescending(o => o.Id).Page(search).ToList();
        return ApiResult.Page(total, items);
    }
    public bool UpdateConfig(ConfConfiguration model)
    {
        Update(model);
        return Save();
    }
    public bool UpdateGroup(ConfGroup model)
    {
        Update(model);
        return Save();
    }
}
